<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <title>角色管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
    <!--<link rel="stylesheet" th:href="@{/css/admin/b-material-img.css">-->
</head>

<body>

<div class="app-page">

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>状态</label></div>
                                    <div class="flex1">
                                        <select name="status" id="">
                                            <option value="">全部</option>
                                            <option value="0">启用</option>
                                            <option value="1">禁用</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>角色名称</label></div>
                                    <div class="flex1">
                                        <input type="text" placeholder="角色名称" name="roleName">
                                    </div>
                                </div>
                            </div>
                            <div style="display: none">
                                <input name="pageNum" th:value="${pageNum}">
                                <input name="pageSize" th:value="${pageSize}">
                            </div>
                            <div class="filter-item">
                                <button class="z-btn z-primary">查询</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">

                    <div class="z-btn-group">
                        <a data-title="创建角色" class="j-btn-control z-btn z-default btn-add">创建角色</a>
                        <a data-title="批量启用" class="j-btn-control z-btn z-default btn-batch-able">批量启用</a>
                        <a data-title="批量禁用" class="j-btn-control z-btn z-default btn-batch-disable">批量禁用</a>
                    </div>

                    <table class="z-table">
                        <thead>
                        <tr>
                            <th>
                                <input type="checkbox" class="input j-checkbox-all">
                            </th>
                            <th>角色名称</th>
                            <th>角色说明</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr th:each="role: ${roleList}"
                            th:attr="data-id=${role.roleId},
                                data-rolename=${role.roleName},
                                data-roledesc=${role.roleDesc},
                                data-super-admin-role=${role.superAdminRole},
                                data-status=${role.status}">
                            <td>
                                <input type="checkbox" class="input j-checkbox">
                            </td>
                            <td th:text="${role.roleName}"></td>
                            <td th:text="${role.roleDesc}"></td>
                            <div th:switch="${role.status}">
                                <td th:case="1">禁用</td>
                                <td th:case="0">启用</td>
                            </div>
                            <div th:switch="${role.superAdminRole}">
                                <!--不是超级管理员角色-->
                                <div th:case="1">
                                    <td class="btn-group" th:switch="${role.status}">
                                        <a class="btn-enable" th:case="1">启用</a>
                                        <a class="btn-disable" th:case="0">禁用</a>
                                        <a class="btn-detail">修改</a>
                                    </td>
                                </div>
                                <div th:case="0">
                                    <td></td>
                                </div>
                            </div>
                        </tr>
                        </tbody>
                    </table>

                    <!-- 分页 -->
                    <div class="app-card-body">
                        <div class="pagination z-pat z-fr"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<!--新增/编辑-->
<div class=" popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close=""></div>
    <div class="section popup-add z-hide">
        <div class="title">创建角色</div>
        <div class="content" id="userForm">
            <form>
                <div class="form-item row" style="display: none">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="hidden" name="roleId" class="roleId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色名称</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入角色名称" class="roleName"
                               name="roleName" data-name="角色名称" data-rule="required">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色说明</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入角色说明" class="roleDesc" name="roleDesc"
                               data-name="角色说明" data-rule="length" maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色权限</label>
                    </div>
                    <div class="body">
                        <input type="text" disabled="disabled" class="authId z-hide moduleIds" name="moduleIds">
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="authName" name="authName">
                            <span class="input-group-addon select-auth"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>状态</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="1" th:text="禁用"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="0" th:text="启用"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close="">取消</a>
            </div>
        </div>
    </div>
    <div class="popup-detail section z-hide"></div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script type="text/javascript" th:inline="javascript">
    //获取context path
    var context = $("meta[name='ctx']").attr("content") || '';
    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    //处理分页
    var pageNum = [[${pageNum}]];
    var pageSize = [[${pageSize}]];
    var total = [[${total}]];
    var pagination = new Pagination(".pagination", {
        pageIndex: pageNum, // 当前页数
        pageSize: pageSize, // 每页数量
        count: total, // 总条数
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function (pageIndex) {
            window.location.href = context + "/role/list?pageNum=" + pageIndex + "&pageSize=" + pageSize;
        }
    })

    $(function () {

        eventEmit();
    })

    function eventEmit() {
        // 新增 - 弹窗打开
        $('.btn-add').click(function () {
            //修改先点击修改，再点击创建时，角色名称显示修改时所拥有的名称
            $('input[name=authName]').val("");
            $('input[name=authIds]').val("");
            popup.open('.popup-add')
        })
        var roleId;
        // 修改 - 弹窗打开
        $('.btn-detail').click(function () {
            var data = $(this).parents('tr')[0].dataset;
            //取值
            roleId = data["id"];

            var rolename = data["rolename"];
            var roledesc = data["roledesc"];
            var status = data["status"];

            //获取角色拥有的权限名称和权限ID
            $.ajax({
                type: "POST",
                url: context + "/role/listModuleNamesByRoleId",
                data: {
                    roleId: roleId
                },
                success: function (obj) {
                    var code = obj.code;
                    console.log(obj);
                    if (code == 0) {
                        var data = obj.data;

                        console.log('data',data)
                        var authName = data.authName;
                        authName = authName.replace("{", "");
                        authName = authName.replace("}", "");

                        $('.popup-detail input[name=authName]').val(authName);
                        $('.popup-detail .moduleIds').val(data.authId);
                    }
                }
            })
            $('.popup-detail').html($('.popup-add').html()).find('.title').text('修改');
            $('.popup-detail').formLoad({
                roleId: roleId,
                roleName: rolename,
                roleDesc: roledesc,
                status: status,
            })
            //获取菜单列表
            popup.open('.popup-detail');
        })

        // 绑定权限
        $(document).on('click', '.select-auth', function () {
            var url = context + '/role/goAuthPicker';

            // 新增
            if ($('.popup-detail').hasClass('z-hide')) {
            }
            // 修改
            else {
                url += '?roleId=' + roleId;
            }

            layer.open({
                type: 2 //此处以iframe举例
                , title: '选择权限'
                , area: ['900px', '500px']
                , maxmin: true
                , content: url
                , btn: ['确定', '取消'] //只是为了演示
                , btnAlign: 'c'
                , yes: function (index, layero) {

                    // todo 获取layer中的数据

                    var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法

                    // alert('在这里获取数据')在这里获取数据

                    // 用iframeWin.functionname() 调用窗口中的方法
                    var data = iframeWin.getTreeData();

                    $('input[name=authName]').val(data.namedata);
                    $('input[name=moduleIds]').val(data.idsdata);

                    layer.close(index) //如果有数据，需进行手工关闭

                }
                , btn2: function (index, layero) {
                    layer.closeAll()
                }

                , zIndex: layer.zIndex //重点1
                , success: function (layero) {
                    layer.setTop(layero) //重点2
                }
            })
        })
    }

    //新增 - 弹窗保存
    var form = $(".popup-add form").form({
        submitSelector: ".popup-add .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {
                moduleIds: $('.popup-add .moduleIds').val(),
            };
            $.each($(".popup-add form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            $.ajax({
                type: "POST",
                url: context + "/role/save",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('创建角色成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/role/list";
                        }, 100);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })


    // 修改 - 弹窗确定
    var form = $(".popup-detail form").form({
        submitSelector: ".popup-detail .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {
                moduleIds: $('.popup-detail .moduleIds').val(),
            };
            $.each($(".popup-detail form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            //修改
            $.ajax({
                type: "POST",
                url: context + "/role/update",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('修改角色成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/role/list";
                        }, 1000);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 批量启用禁用角色
    $('.btn-batch-able, .btn-batch-disable').click(function () {
        var status = 0;
        var optName = "批量启用";
        if($(this).hasClass('btn-batch-disable')){
            status = 1;
            optName = "批量禁用";
        }

        let idArr = [];
        var hasSuperAdminUser = false;
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                var superAdminUser = $(this).parents('tr,.tr').data('superAdminRole');
                var id = $(this).parents('tr,.tr').data('id');
                if(superAdminUser == 0){
                    //是超级管理员角色不能操作
                    hasSuperAdminUser = true;
                    return;
                } else {
                    idArr.push(id);
                }
            }
        })
        if(hasSuperAdminUser){
            popup.tipsTop('选择的角色中包含超级管理员角色，请确认', 'warning');
            return;
        }
        var ids = idArr.join(',');
        if(isBlank(ids)){
            popup.tipsTop('请选择需要'+optName+'的角色', 'warning');
            return;
        }
        $.ajax({
            type: "POST",
            url: context + "/role/batchAbleDisable",
            data: {
                ids: ids,
                status: status
            },
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    popup.tipsTop((optName + '成功'), 'success');
                    setTimeout(function () {
                        //跳转到角色列表
                        window.location.href = context + "/role/list";
                    }, 1000);
                } else {
                    popup.tipsTop(obj.msg, 'warning');
                }
            }
        })
    })

    // 启用/禁用
    $('.btn-disable,.btn-enable').click(function () {
        var data = $(this).parents('tr')[0].dataset;
        var id = data["id"];
        //默认（0：启用）
        var status = 0;
        if ($(this).hasClass('btn-enable')) {
            $.ajax({
                type: "POST",
                url: context + "/role/enableDisableRole",
                data: {
                    roleId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('enable', '启用角色成功');
                        //跳转到用户列表
                        window.location.href = context + "/role/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        } else {
            //禁用
            status = 1;
            $.ajax({
                type: "POST",
                url: context + "/role/enableDisableRole",
                data: {
                    roleId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('disable', '禁用角色成功');
                        //跳转到用户列表
                        window.location.href = context + "/role/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    //检查参数
    function isBlank(param) {
        if(undefined === param){
            return true;
        }
        if(null == param){
            return true;
        }
        if("" === param){
            return true;
        }
        return false;
    }
</script>
</body>

</html>